<?php

namespace app\common\model;

use think\Model;

/**
 * 会员模型
 */
class User Extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
    ];


    /**
     * 获取个人URL
     * @param   string  $value
     * @param   array   $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }

    /**
     * 获取头像
     * @param   string    $value
     * @param   array     $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        return $value ? $value : '/assets/img/avatar.png';
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param   string    $value
     * @param   array     $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array) json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object) $value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员积分
     * @param int $score    积分
     * @param int $user_id  会员ID
     * @param string $memo  备注
     */
    public static function score($score, $user_id, $memo)
    {
        $user = self::get($user_id);
        if ($user) {
            $before = $user->score;
            $after = $user->score + $score;
            $level = self::nextlevel($after);
            //更新会员信息
            // $user->save(['score' => $after, 'level' => $level]);
            $user->save(['score' => $after, 'group_id' => $level]);
            //写入日志
            ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
        }
    }
    // 变更会员财富宝
    public static function money($user_id, $money, $type, $memo='', $other_user_id=0)
    {

        $user = self::get($user_id);
        if ($user && $money) {
            $before = $user->money;
            $after = $user->money + $money;
            $user->save(['money' => $after]);
            //写入日志
            MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo, 'date' => date('Ymd'), 'type' => $type, 'other_user_id' => $other_user_id]);
            return true;
        }
        return false;
    }


    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        /*$lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value)
        {
            if ($score >= $value)
            {
                $level = $key;
            }
        }
        return $level;*/

        $map = [
            'status'=>'normal',
            'bkc_num_min'=>['elt', $score],
            'bkc_num_max'=>['egt', $score],
        ];
        $level = db('UserGroup')->field('id')->order('bkc_num_min desc')->where($map)->find();

        return isset($level['id']) ? $level['id'] : 1;
    }

    /**
     * 获取某用户的个人团队
     * @param array $teamList 所有用户
     * @param int $myid 当前用户ID
     * @return array
     */
    /*public function getTeam($teamList, $myid)
    {
        $newarr = [];
        foreach ($teamList as $key=>$value)
        {
            if (!isset($value['id']))
                continue;
            if ($value['node_parent_id'] == $myid)
            {
                unset($teamList[$key]);

                $item = $value;
                $child = $this->getTeam($teamList, $value['id']);
                if ($child) {
                    $item['child'] = $child;
                }
                $newarr[]=$item;
            }
        }
        return $newarr;
    }*/
    // 一次性获取
    /*public function getAllTeam($teamList, $myid=0)
    {
        foreach ($teamList as $key => &$value) {
            // if ($value['id']!=$myid && $value['node_parent_id'] < $myid) {
            //     unset($teamList[$key]);
            // }
            if (isset($teamList[$value['node_parent_id']])) {
                $teamList[$value['node_parent_id']]['child'][] = $value;
                unset($teamList[$key]);
            }
            if ($value['id']==$myid) {
                return $value;
            }
        }
        return $teamList;
    }*/
    // 单次获取至第三层
    public function getTeam($id)
    {
        $field = 'id,group_id,username,createtime,node_parent_id,user_code';

        $userList = db('User')->where('node_parent_id', $id)->field($field)->select();
        foreach ($userList as $key=>&$value)
        {
            $value['child'] = db('User')->where('node_parent_id', $value['id'])->field($field)->select();
        }
        return $userList;
    }
    // 获取用户的团队人数
    /*public function getTeamNum($id)
    {
        static $teamNum=0;

        $userList = db('User')->where('node_parent_id', $id)->column('id');
        foreach ($userList as $key=>$value)
        {
            $this->getTeamNum($value);
            $teamNum++;
        }
        return $teamNum;
    }*/
    public function getTeamNum($id)
    {
        $teamNum=0;

        $userList = db('User')->where('node_parent_id', $id)->column('id');
        foreach ($userList as $key=>$value)
        {
            $teamNum += $this->getTeamNum($value);
            $teamNum ++;
        }
        return $teamNum;
    }
    // 获取所有团队的业绩
    public function getTeamAmount()
    {
        $list = db('User')->order('node_parent_id', 'desc')->column('id,money,score,group_id,node_parent_id');
        foreach ($list as $key => &$value) {
            if (isset($list[$value['node_parent_id']])) {
                $amount = $value['score']+$value['money'];
                /*if ($amount>0) {
                    $child_amount = 0;
                    if (isset($value['amount'])) {
                        $child_amount = array_sum($value['amount']);
                    }
                    $list[$value['node_parent_id']]['amount'][] = $amount+$child_amount;
                }*/

                    $child_amount = 0;
                    if (isset($value['amount'])) {
                        $child_amount = array_sum($value['amount']);
                    }
                    $amount += $child_amount;
                if ($amount>0) {
                    $list[$value['node_parent_id']]['amount'][] = $amount;
                }


            }
        }
        return $list;
    }


    /**
     * 获取用户的多代下线
     * @param int $pid 当前用户ID
     * @return array
     */
    public static function getChildren($pid, $limit = 1, $level = 0, &$children = [])
    {
        $level++;
        $map = [
            'parent_id'=>$pid,
        ];
        $list = db('User')->field('id, group_id, score')->where($map)->select();
        if ($list) {
            foreach ($list as $key => $value) {
                $children[$level][] = $value;
                if ($limit>$level) {
                    self::getChildren($value['id'], $limit, $level, $children);
                }
            }
        }
        return $children;
    }
    // 获取用户的直推下线人数
    public function getChildrenNum($id)
    {
        static $teamNum=0;

        $userList = db('User')->where('parent_id', $id)->column('id');
        foreach ($userList as $key=>$value)
        {
            $this->getChildrenNum($value);
            $teamNum++;
        }
        return $teamNum;
    }

    /**
     * 返佣
     * @param int $user_id  会员ID
     * @param int $money    财富宝
     * @param int $before    原有财富宝
     * @param int $date    日期
     * @param string $memo  备注
     */
    protected static function rebate($user_id, $money, $before, $date, $type=1)
    {
        if ($money && $user_id) {

            $type_arr = [
                1=>['memo'=>'静态算力', 'field'=>'static_rebate_date'],
                2=>['memo'=>'分享算力', 'field'=>'dynamic_rebate_date'],
                3=>['memo'=>'共享算力', 'field'=>'dynamic_rebate_date'],
            ];
            $type_item = isset($type_arr[$type]) ? $type_arr[$type] : $type[1];

            $after = $money + $before;
            //更新会员信息
            // model('User')->save(['money' => $after, $type_item['field'] => $date], ['id' => $user_id]);
            db('User')->where(['id' => $user_id])->update(['money' => $after, $type_item['field'] => $date]);

            //写入日志
            MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $type_item['memo'], 'date' => $date, 'type' => $type]);
        }
    }
    public static function staticRebate($user_id, $money, $before, $date)
    {
        self::rebate($user_id, $money, $before, $date);
    }
    public static function dynamicRebate($user_id, $money, $before, $date, $type=2)
    {
        self::rebate($user_id, $money, $before, $date, $type);
    }
    // 财富宝发送
    public static function moneyTransfer($from_id, $to_id, $money)
    {
        $from_user = self::get($from_id);
        $to_user = self::get($to_id);
        if ($from_user && $to_user) {

            $date = date('Ymd');
            $before = $from_user->money;
            $after = $from_user->money - $money;
            //更新会员信息
            $from_user->save(['money' => $after]);
            //写入日志
            MoneyLog::create(['user_id' => $from_id, 'other_user_id' => $to_id, 'money' => -$money, 'before' => $before, 'after' => $after, 'memo' => '财富宝发送', 'type' => 4, 'date' => $date]);

            $before = $to_user->money;
            $after = $to_user->money + $money;
            //更新会员信息
            $to_user->save(['money' => $after]);
            //写入日志
            MoneyLog::create(['user_id' => $to_id, 'other_user_id' => $from_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => '财富宝收款', 'type' => 5, 'date' => $date]);

            return true;
        }
        return true;
    }
    // 财富宝冻结
    public static function moneyFrozen($user_id, $money)
    {

        $user = self::get($user_id);
        if ($user && $money) {
            $before = $user->money;
            $after = $user->money - $money;
            $frozen_money = $user->frozen_money + $money;
            $user->save(['money' => $after, 'frozen_money' => $frozen_money]);
            //写入日志
            MoneyLog::create(['user_id' => $user_id, 'money' => -$money, 'before' => $before, 'after' => $after, 'memo' => '财富宝冻结', 'date' => date('Ymd'), 'type' => 6]);
            return true;
        }
        return false;
    }
    // 生成钱包地址
    public function createWalletAddress($user_id)
    {
        $user = db('User')->field('id, createtime, wallet_address')->where('id', $user_id)->find();
        if (empty($user['wallet_address'])) {
            $wallet_address = md5($user['id'].$user['createtime']).rand(1,9);
            db('User')->where('id', $user_id)->setField('wallet_address', $wallet_address);
            return $wallet_address;
        }
        return $user['wallet_address'];
    }

    // 生成会员ID（推荐码）
    public function createUsername()
    {
        $username = getRandChar();
        $user = db('user')->field('id')->where('user_code', $username)->find();
        if (empty($user)) {
            return $username;
        }else{
            return $this->createUsername();
        }

    }

}
